#include "threadPool.h"

int exitPipe[2];

void handler(int signum){
    printf("signum = %d\n", signum);
    write(exitPipe[1],"1",1);
}

int main (int argc,char *argv[]){
    char netip[]="172.21.76.123";
    char netport[] ="20001";
    // if(argc != 4){
    //     LOG(LOG_LEVEL_ERROR, 
    //         "system", "argc num is worong num");
    //    return -1;     
    // }
    LOG(LOG_LEVEL_INFO, 
        "system", "argv is %s, %s, %s,%s", 
        argv[1], argv[2], argv[3], argv[4]);
    
    pipe(exitPipe);

    if(fork()){
        close(exitPipe[0]);
        signal(SIGUSR1, handler);
        wait(NULL);
        LOG(LOG_LEVEL_DEBUG, 
            "system", "parent process exit");
        exit(0);
    }

    close(exitPipe[1]);
    threadPool_t threadPool;
    // int workerNum = atoi(argv[4]);
    int workerNum = 4; // Default worker number
    threadPoolInit(&threadPool, workerNum);
    makeWorker(&threadPool);
    //int sockfd = tcpInit(argv[1],argv[2]);
    int sockfd = tcpInit(netip,netport);
    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitPipe[0]);
    struct epoll_event readyset[1024];

    while(1){
        int readynum = epoll_wait(epfd, readyset, 1024, -1);

        for(int i=0; i < readynum;i++){

            if(readyset[i].data.fd == sockfd){
                int netfd = accept(sockfd,NULL,NULL);
                LOG(LOG_DEBUG,"system","");

                printf("连接成功\n");
                //生产者生产加锁
                pthread_mutex_lock(&threadPool.mutex);
                enQueue(&threadPool.taskQueue, netfd);
                printf("成功入队\n");
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }else if(readyset[i].data.fd == exitPipe[0]){
                LOG(LOG_DEBUG,"system","");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);

                for(int j = 0; j < workerNum; ++j){
                    free(threadPool.pthreadContext->pstack);
                    pthread_join(threadPool.tidArr.arr[j],NULL);
                }
                LOG(LOG_DEBUG,"system","");
                exit(0);
            }

            

        }
    }


    return 0;

}
